package com.yonyou.ucf.mdf.app.isvdxq.secondpart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.common.ApiYon;
import com.yonyou.ucf.mdf.app.isvdxq.common.DxqConfig;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.RfidCodebind;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderNoticeEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.OrderNoticeService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.OtherInAndOut.CheckResultOtherInAndOutDto;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.service.CheckStockService;
import com.yonyou.ucf.mdf.app.isvdxq.other.model.AccessTokenResponse;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.CheckdiffEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.CheckresultEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.StorerecordEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.BaseParamBean;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.OtherInDataForCheckParam;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.model.OtherInRecordBean;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.*;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import com.yonyou.ucf.mdf.app.isvdxq.utils.RequestTool;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = {DxqConfig.pre_apiUrl+"/epcother",DxqConfig.pre_pcUrl+"/epcother"})
public class EpcotherController {
    private static final Logger logger = LoggerFactory.getLogger(EpcotherController.class);

    @Autowired
    private BaseService baseService;

    @Autowired
    private EpcpickService epcpickService;
    @Autowired
    private EpclistService epclistService;
    @Autowired
    private StorerecordService storerecordService;
    @Autowired
    private OrderNoticeService orderNoticeService;

    @Autowired
    private EpcotherService epcotherService;
    @Autowired
    private TaglistService taglistService;
    @Autowired
    private CheckStockService checkStockService;

    @RequestMapping("/ViewPage")
    public DataResult ViewPage(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        try {
            Map params = RequestTool.getParamsPage(request, result);
            int pagenum = result.getPageNum();
            int pagesize = result.getPageSize();
            int m = result.initStartNumber();
            List<StorerecordEntity> dataList = storerecordService.SelectPage(tenantId, m, pagesize);
            result = new DataResult(1, "操作成功");
            result.setDataList(dataList);
        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 所有数据列表
     * /apidxq/isv2/epcother/ViewList
     *
     * @param request
     * @return
     */
    @RequestMapping("/ViewList")
    public DataResult ViewList(HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        //接收参数
        String tenantId = baseService.getTenantId(request);
        try {
            Map params = RequestTool.getParams(request);
            List<StorerecordEntity> dataList = storerecordService.SelectAll(tenantId);
            result = new DataResult(1, "操作成功");
            result.setDataList(dataList);

            if (params.containsKey("type") && params.get("type").equals("checkdiff")) {
                List<CheckdiffEntity> myList = storerecordService.SelectAllForCheckdiff(tenantId);
                result.setDataList(myList);
            } else if (params.containsKey("type") && params.get("type").equals("checkresult")) {
                List<CheckresultEntity> myList = storerecordService.SelectAllForCheckresult(tenantId);
                result.setDataList(myList);
            }

        } catch (Exception ex) {
            result.setMessage(ex.getMessage());
        }

        return result;
    }

    /**
     * 盘盈 [===发签入库]
     * 盘盈入库 ordertype=4  orderid=存盘点单id  coderfid表 字段rfid_status=7 盘点补录
     * 库存状态rfid_status: 0入库未上架-分配完标签后的状态 1在库正常 2停用 3标签损坏-1删除 4拣货 5配货 6发货出库
     * 关键流程：入库tag,epc,record
     *
     * @param tenant_id
     * @param CodeBindList
     * @return
     */
    @PostMapping("/BindEpcSubmitForPanYing")
    public DataResult BindEpcSubmitForPanYing(String tenant_id, String tag, @RequestBody List<RfidCodebind> CodeBindList, HttpServletRequest request) {
        DataResult result = new DataResult(0, "操作失败");
        if (CodeBindList.size() == 0) return result;
        try {
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            List<String> epcs = CodeBindList.stream().map(it -> it.getRfid_code())
                    .distinct().collect(Collectors.toList());
            List<EpcEntity> list_epcEntity = epclistService.SelectByEpcs(epcs, tenant_id);
            boolean checkFlag = EpcotherService.CheckEpcUsed(list_epcEntity);
            if (checkFlag) {
                result.setMessage("标签已占用");
                return result;
            }

            result = epcotherService.BindEpcSubmit(CodeBindList, tag);
        } catch (Exception ex) {
            String logtxt = "[BindEpcSubmitForPanYing]" + ex.getMessage();
            System.out.println(logtxt);
            logger.error(logtxt);
        }
        return result;
    }

    /**
     * 盘盈入库 改成批量入库，增加备注，行号（行号1开始）
     * ordertype=4 仅支持盘点补录
     *
     * @param incomeIdString
     * @param tenant_id
     * @return
     * @throws IOException
     * @throws Exception
     */
    @RequestMapping("/CheckStockAutoCreateOtherInOrder")
    public DataResult AutoCreateOtherInOrder(String incomeIdString, String tenant_id, HttpServletRequest request) {
        DataResult dataResult = new DataResult(0, "单据回传失败");
        String ordertype = "4"; //盘点补签入库
        List<String> ids = new ArrayList<>();
        if (!StringUtils.isEmpty(incomeIdString)) {
            ids = MyTool.StringRemoveLastSymbolToList(incomeIdString, ",");
        }
        if (StringUtils.isBlank(incomeIdString) || ids.size() == 0) return dataResult;
        try {
            String tenantId = baseService.getTenantId(request);
            tenantId = !StringUtils.isEmpty(tenant_id) ? tenant_id : tenantId;

            int orderCount = 0;
            List<CheckResultOtherInAndOutDto> checkResultOtherInAndOutDtos = checkStockService.OtherInOrOutOrderByCheckStockIncome(ids, 2, tenantId);
            if (checkResultOtherInAndOutDtos.size() > 0) {
                // 重复提交验证
                List<String> epcList = checkResultOtherInAndOutDtos.stream().map(it -> it.getEpccode()).distinct().collect(Collectors.toList());
                List<EpcEntity> epcEntityList = epclistService.SelectByEpcs(epcList, tenantId);
                long checkNum = epcEntityList.stream().filter(it -> it.getRfid_status() == 1).count();
                if (checkNum > 0) {
                    dataResult = new DataResult(1, "数据已处理，无需重复提交");
                    return dataResult;
                }
                // 获取Token
                AccessTokenResponse res = baseService.getAccessToken3(tenantId);
                String accessToken = res.getAccessToken();
                String gatewayUrl = baseService.buildBusinessUrl(tenantId);
                Map<String, Object> params = new HashMap<>();
                String url = gatewayUrl + ApiYon.getOthinSubmit + "?access_token=" + accessToken;
                String submitcheckKey = MyTool.GenerateTime("yyyyMMddHHmmssSSS");

                OtherInDataForCheckParam data = new OtherInDataForCheckParam();
                CheckResultOtherInAndOutDto checkResultOtherInAndOutDto = checkResultOtherInAndOutDtos.get(0);
                String orgId = checkResultOtherInAndOutDto.getOrgId();

                data.setResubmitCheckKey(submitcheckKey);
                data.setOrg(orgId);
                data.setAccountOrg(checkResultOtherInAndOutDto.getAccountOrg());
                data.setWarehouse(checkResultOtherInAndOutDto.getWarehouseCode());
                data.setVouchdate(MyTool.GenerateTime("yyyy-MM-dd")); // 设置时间
                data.setBustype(DxqConfig.transtype_otherin);
                data.set_status("Insert");
                List<OtherInRecordBean> recordList = new ArrayList<>();
                int i = 0;
                int countEPC = 0;
                for (CheckResultOtherInAndOutDto item : checkResultOtherInAndOutDtos) {

                    i++;
                    OtherInRecordBean records = new OtherInRecordBean();

                    // todo 数量和其他内容的验证
                    records.setProduct(item.getStockId());
                    records.setProductsku(item.getStockSkuId());
                    records.setUnit(item.getUnitId());
                    records.setQty(item.getLabelCount());
                    String str = String.valueOf(item.getUnitExchangeType());

                    if (item.getMainUnitCount() == null) {
                        records.setUnitExchangeType(1);
                        records.setSubQty(item.getLabelCount());
                        records.setInvExchRate(BigDecimal.ONE);
                    } else {
                        records.setUnitExchangeType(item.getUnitExchangeType());
                        BigDecimal b = item.getMainUnitCount();
                        BigDecimal c = new BigDecimal(0);
                        // 计算件数
                        if (b.longValue() > c.longValue()) {
                            long subqty = item.getLabelCount().longValue() / b.longValue();
                            BigDecimal d = new BigDecimal(subqty);
                            records.setSubQty(d);
                        }
                        records.setInvExchRate(item.getMainUnitCount());
                    }

                    records.setStockUnitId(item.getStockUnit());

                    // 生产批次和有效期
                    records.setBatchno(item.getBatchno());
                    records.setProducedate(item.getProductDate());
                    if (!StringUtils.isEmpty(item.getInvalidDate())) {
                        records.setInvaliddate(item.getInvalidDate());
                    }
                    records.setMemo(MyTool.makeMemoForDetail("dxq_storerecord", "1", item.getEpccode()));
                    records.setRowno(i);
                    records.set_status("Insert");
                    recordList.add(records);
                    countEPC++;
                }
                if (recordList.size() == 0) {
                    dataResult.setMessage("没有相应单据信息请检查提交的数据");
                    return dataResult;
                }
                String batch_no = MyTool.GenerateBatchnoDXQ(ordertype);
                data.setMemo(MyTool.makeMemo(batch_no, countEPC));
                data.setOthInRecords(recordList);
                params.put("data", data);

                String resString = RequestTool.doPost(url, JSON.toJSONString(params));
                JSONObject jsonObject = JSONObject.parseObject(resString);
                if (jsonObject.getString("code").equals("200")) {
                    // 回写对应单据的状态
                    String dataDetail = jsonObject.getString("data");
                    dataResult = storerecordService.UpdateForCallback(checkResultOtherInAndOutDtos, tenantId, ordertype, dataDetail, batch_no);
                    if (dataResult.getStatus() != 1) {
                        try {
                            OrderNoticeEntity recordEntity = new OrderNoticeEntity();
                            recordEntity.setTenant_id(tenantId);
                            recordEntity.setActioncode("pc_callback");
                            recordEntity.setPickbatchno(batch_no);
                            recordEntity.setType(DxqConfig.TypeFail); //本地回写失败
                            recordEntity.setRemarkyonyou(dataDetail);
                            recordEntity.setRemarkdxq(JSONObject.toJSONString(checkResultOtherInAndOutDtos));
                            recordEntity.setRemark(ordertype);
                            recordEntity.setStatus(0);
                            orderNoticeService.InsertEntity(recordEntity);
                        } catch (Exception ex) {
                            System.out.println("[其他入库]" + ex.getMessage());
                        }
                        dataResult.setStatus(1);
                        dataResult.setMessage("本地回写失败");
                        return dataResult;
                    }
                    orderCount = recordList.size();
                } else {
                    String Message = jsonObject.getString("message");
                    if (orderCount > 0) {
                        Message += "本次共提交【" + checkResultOtherInAndOutDtos.size() + "条数据】其中 【 " + orderCount + " 】条数据完成其他出库创建";
                    }
                    dataResult.setMessage(Message);
                    return dataResult;
                }
                dataResult.setMessage("成功将 【 " + orderCount + " 】条数据完成其他入库创建");
                return dataResult;
            } else {
                dataResult.setMessage("没有相应单据信息请检查提交的数据");
                return dataResult;
            }
        } catch (Exception ex) {
            dataResult.setMessage(ex.getMessage());
            System.out.println(JSONObject.toJSONString(dataResult));
        }
        return dataResult;
    }

    /**
     * 单据锁定检测 data=true 判断规则单据是否存在 true 是 false 不存在
     * 锁整单
     * @param request
     * @return
     */
    @RequestMapping("/checkRecord")
    public DataResult CheckRecord(HttpServletRequest request) {
        DataResult result = new DataResult(1, "操作成功");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> myParams = RequestTool.getParams(request);
            String poid = myParams.get("poid");
            String memo = myParams.get("memo");
            String data = myParams.get("data");
            if (StringUtils.isNotEmpty(data)) {
                List<BaseParamBean> jsonObject = JSONObject.parseArray(data, BaseParamBean.class);
                List<String> codes = jsonObject.stream().map(it -> it.getCode()).distinct().collect(Collectors.toList());
            }
            List<String> memoList = new ArrayList<>();
            if (StringUtils.isNotEmpty(memo)) memoList = Arrays.asList(memo.split("\\|"));
            StorerecordEntity storerecordEntity = storerecordService.SelectEntityByPoid(poid, tenantId);
            if (storerecordEntity == null) {
                result.setData(false);
            } else {
                result.setData(true);
            }
        } catch (Exception ex) {
            result.setStatus(0);
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    @RequestMapping("/checkRecordByCodes")
    public DataResult CheckRecordByCodes(HttpServletRequest request) {
        DataResult result = new DataResult(1, "操作成功");
        try {
            //接收参数
            String tenantId = baseService.getTenantId(request);
            String userId = RequestTool.getHeaderAndParameter(request, DxqConfig.DXQ_userId);
            Map<String, String> myParams = RequestTool.getParams(request);
            String data = myParams.get("data");
            if (StringUtils.isEmpty(data)) {
                result.setStatus(0);
                result.setMessage("参数异常");
                return result;
            }
            List<BaseParamBean> jsonObject = JSONObject.parseArray(data, BaseParamBean.class);
            List<String> codes = jsonObject.stream().map(it -> it.getCode()).distinct().collect(Collectors.toList());
            List<StorerecordEntity> storerecordEntityList = storerecordService.SelectEntityByCodes(codes, tenantId);
            if (storerecordEntityList == null || storerecordEntityList.size() == 0) {
                result.setData(false);
            } else {
                result.setData(true);
                result.setMessage(String.format("单号[%s]锁定,禁止操作", storerecordEntityList.get(0).getPocode()));
            }
        } catch (Exception ex) {
            result.setStatus(0);
            result.setMessage(ex.getMessage());
        }
        return result;
    }


}
